﻿
using Alison.EFCore.Dto;
using Alison.Service;
using Alison.Tools.HttpContact.Response; 
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Alison.API.Tools.Jwt
{

	/// <summary>
	/// 登录验证接口
	/// </summary>
	public class TokenAuthenticationService : IAuthenticateService
	{ 
		private readonly IUserService _userService;
		private readonly TokenManagement _tokenManagement;
		public TokenAuthenticationService(
			IUserService userService, 
			IOptions<TokenManagement> tokenManagement) { 
			_userService = userService;
			_tokenManagement = tokenManagement.Value;
		}
		public void IsAuthenticated(LoginDTO request, out ApiResponse token) {
		
			ApiResponse response = _userService.Login(request);
			if (response.StatusCode != 200) {
				token = response;
				return;
			}
			var claims = new[]
			{
				new Claim(ClaimTypes.Name,request.Username)
			};
			var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
			var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
			var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims,
				expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
				signingCredentials: credentials);

			token = response;
			token.Result  = new JwtSecurityTokenHandler().WriteToken(jwtToken);
			 
		}
	}
}
